#include <nds.h>
#include <stdlib.h>
 
#define NUM_STARS 40
#define STARS_BGCOLOR RGB15(0,0,0)
 
typedef struct 
{
	int x;
	int y;
	int speed;
	unsigned short color;
 
}Star;
 
 
 
void MoveStar(Star* star)
{
	star->x += star->speed;
 
	if(star->x >= SCREEN_WIDTH)
	{
		star->color = RGB15(31,31,31);
		star->x = 0;
		star->y = rand() % 192;
		star->speed = rand() % 4 + 1;	
	}
}
 
void ClearScreen(u16 *screen_buffer)
{
     int i;
     
     for(i = 0; i < 256 * 192; i++)
           screen_buffer[i] = STARS_BGCOLOR;
}
 
void InitStars(Star *stars, uint8_t stars_length)
{
	int i;
 
	for(i = 0; i < stars_length; i++)
	{
		stars[i].color = RGB15(31,31,31);
		stars[i].x = rand() % 256;
		stars[i].y = rand() % 192;
		stars[i].speed = rand() % 4 + 1;
	}
}

void DrawStar(Star* star, u16 *screen_buffer)
{
	screen_buffer[star->x + star->y * SCREEN_WIDTH] = star->color;
}
 
void EraseStar(Star* star, u16 *screen_buffer)
{
	screen_buffer[star->x + star->y * SCREEN_WIDTH] = STARS_BGCOLOR;
}

u16 *SetupScreenBuffer(void)
{
	videoSetMode(MODE_FB0);
	vramSetBankA(VRAM_A_LCD);

	return VRAM_A;
}

int main(void) 
{
	int i;
	u16 *screen_buffer;
	Star stars[NUM_STARS];
 
	irqInit();
	irqEnable(IRQ_VBLANK);
 
	screen_buffer = SetupScreenBuffer();

    ClearScreen(screen_buffer);
	InitStars(stars, NUM_STARS);
 
	//we like infinite loops in console dev!
	while(1)
	{
		swiWaitForVBlank();
	
		for(i = 0; i < NUM_STARS; i++)
		{
			EraseStar(&stars[i], screen_buffer);
 
			MoveStar(&stars[i]);
 
			DrawStar(&stars[i], screen_buffer);
		}		
	}
 
	return 0;
}
